package china.z.console.config.datasources;

import china.z.console.config.datasources.dynamic.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zengyz
 * @date 2018-01-01
 *  数据源配置
 */
@Configuration
public class DatasourceConfiguration {

    @Bean(name = "firstDS")
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource dataSourceFirst() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondDS")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource dataSourceSecond() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDatasources")
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(dataSourceFirst());

        //配置多数据源
        Map<Object, Object> datasourceMap = new HashMap<>(5);
        datasourceMap.put("first", dataSourceFirst());
        datasourceMap.put("second", dataSourceSecond());

        dynamicDataSource.setTargetDataSources(datasourceMap);

        return dynamicDataSource;
    }

}
